const httpStatus = require('http-status');
const Admin = require('../models/admin.model');
const ApiError = require('../utils/ApiError');

/**
 * 创建管理员
 * @param {Object} adminBody
 * @returns {Promise<Admin>}
 */
const createAdmin = async (adminBody) => {
  if (await Admin.isUsernameTaken(adminBody.username)) {
    throw new ApiError(httpStatus.BAD_REQUEST, '用户名已被使用');
  }
  return Admin.create(adminBody);
};

/**
 * 通过用户名获取管理员
 * @param {string} username
 * @returns {Promise<Admin>}
 */
const getAdminByUsername = async (username) => {
  return Admin.findOne({ username });
};

/**
 * 通过ID获取管理员
 * @param {ObjectId} id
 * @returns {Promise<Admin>}
 */
const getAdminById = async (id) => {
  return Admin.findById(id);
};

/**
 * 更新管理员
 * @param {ObjectId} adminId
 * @param {Object} updateBody
 * @returns {Promise<Admin>}
 */
const updateAdminById = async (adminId, updateBody) => {
  const admin = await getAdminById(adminId);
  if (!admin) {
    throw new ApiError(httpStatus.NOT_FOUND, '管理员不存在');
  }
  if (updateBody.username && (await Admin.isUsernameTaken(updateBody.username, adminId))) {
    throw new ApiError(httpStatus.BAD_REQUEST, '用户名已被使用');
  }
  Object.assign(admin, updateBody);
  await admin.save();
  return admin;
};

/**
 * 删除管理员
 * @param {ObjectId} adminId
 * @returns {Promise<Admin>}
 */
const deleteAdminById = async (adminId) => {
  const admin = await getAdminById(adminId);
  if (!admin) {
    throw new ApiError(httpStatus.NOT_FOUND, '管理员不存在');
  }
  await admin.remove();
  return admin;
};

module.exports = {
  createAdmin,
  getAdminByUsername,
  getAdminById,
  updateAdminById,
  deleteAdminById,
}; 